package me.xinping.libs.utils

import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat

/**
 * 权限工具.
 * <p>
 * Date 2018/12/4
 * @author fanxinping_cd@keruyun.com
 */
object PermissionUtils {

    /**
     * 动态请求权限的request_code
     */
    const val CODE_REQUEST_PERMISSION = 101
    /**
     * 打开应用的权限页面
     */
    const val CODE_REQUEST_PERMISSION_SETTING = 102


    /**
     * 打开应用的权限设置页面
     */
    fun startPermissionSetting(activity: Activity) {
        val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
        val uri = Uri.fromParts("package", activity.packageName, null)
        intent.data = uri
        activity.startActivityForResult(intent, CODE_REQUEST_PERMISSION_SETTING)

    }

    /**
     * 检查是否有某项权限，true-yes
     */
    fun checkPermission(activity: Activity, permission: String): Boolean =
            ContextCompat.checkSelfPermission(activity, permission) == PackageManager.PERMISSION_GRANTED

    /**
     * 检查是否有某项权限，没有，就再次申请,若有权限则直接执行lambda
     */
    fun checkPermission(
            activity: Activity,
            permissions: Array<String>,
            requestedLambda: (isSuccess: Boolean) -> Unit = {}
    ) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            var isCheckPass = true
            for (permission in permissions) {
                if (!checkPermission(activity, permission)) {
                    isCheckPass = false
                    break
                }
            }
            if (!isCheckPass) {
                startRequestPermission(activity, permissions)
                requestedLambda.invoke(false)
            } else {
                requestedLambda.invoke(true)
            }
        } else {
            requestedLambda.invoke(true)
        }
    }

    /**
     * 请求权限
     */
    fun startRequestPermission(activity: Activity, permissions: Array<String>) {
        ActivityCompat.requestPermissions(activity, permissions, CODE_REQUEST_PERMISSION)
    }


}